/*
 * @Date: 2025-09-02 22:49:40
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-15 23:19:57
 * @FilePath: /admin-vue/src/composables/system/useRole.ts
 */
import { http } from '@/plugins/axios'

export default () => {
  const loading = ref(false)
  const collection = ref<ResponsePageResult<RoleModel>>()
  const params = ref({
    key: '',
    page: 1,
    per_page: 5,
  })
  const model = ref<RoleModel>()

  const load = async () => {
    loading.value = true
    collection.value = await http.request<RoleModel[], ResponsePageResult<RoleModel>>({
      url:
        `role?` +
        Object.entries(params.value)
          .map(([k, v]) => `${k}=${v}`)
          .join('&'),
    })
    loading.value = false
  }

  const find = async (id: any) => {
    const { data } = await http.request<RoleModel>({
      url: `role/${id}`,
    })
    return data
  }

  const add = async (model: RoleModel) => {
    const data = await http.request({ url: 'role', method: 'POST', data: model })
    return data
  }

  const update = async (model: RoleModel) => {
    const data = await http.request<any, ResponseResult<any>>({
      url: `role/${model.id}`,
      method: 'PUT',
      data: model,
    })
    return data
  }

  const del = async (id: any) => {
    await http.request({ url: `role/${id}`, method: 'DELETE' })
    load()
  }

  const rolePermissions = async (id: number) => {
    const { data } = await http.request<number[]>({
      url: `role/${id}/permissions`,
      data: model,
    })
    return data
  }

  const syncRolePermissions = async (id: number, permissions: number[]) => {
    const data = await http.request({
      url: `role/${id}/permissions`,
      method: 'POST',
      data: { permissions },
    })
    return data
  }

  const roles = async () => {
    const { data } = await http.request<TransferOptionType[]>({
      url: `role/all`,
    })
    return data
  }

  return {
    loading,
    collection,
    params,
    model,
    load,
    find,
    add,
    update,
    del,
    rolePermissions,
    syncRolePermissions,
    roles,
  }
}
